package cn.pengpeng.zk.crud;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

/**
 * ZOOKEEPER的数据增删改查
 * @author root
 *
 */
public class ZKCRUD {
	private static final String connetString = "bigdata01:2181,bigdata02:2181";
	private int sessionTimeout = 2000;
	ZooKeeper zkClient = null;
	@Before
	public void init() throws Exception{
		zkClient = new ZooKeeper(connetString, sessionTimeout, new Watcher() {
			
			@Override
			public void process(WatchedEvent event) {
				System.out.println(event.getType()+"+ +"+event.getPath());
				try {
					zkClient.getChildren("/", true);
				} catch (KeeperException | InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}
	/**
	 * 数据的增删改查
	 * @throws Exception 
	 * @throws  
	 */
	@Test
	public void testCreate() throws Exception{
		// 参数1：要创建的节点的路径 参数2：节点大数据 参数3：节点的权限 参数4：节点的类型
		String create = zkClient.create("/app2", "hellozk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		//上传的可以是什么的数据类型，但是需要转换成byte[]
		System.out.println(create);
	}
	@Test
	public void testExist() throws KeeperException, InterruptedException{
		Stat stat = zkClient.exists("/eclipse", false);
		System.out.println(stat);
	}
	@Test
	public void getClildren() throws KeeperException, InterruptedException{
		List<String> list = zkClient.getChildren("/", true);
		for (String string : list) {
			System.out.println(string);
		}
		Thread.sleep(1000*60*2);
	}
	@Test
	public void getData() throws KeeperException, InterruptedException{
		byte[] data = zkClient.getData("/eclipse", false, null);
		System.out.println(new String(data));
	}
	public void deleteZnode() throws InterruptedException, KeeperException{
		zkClient.delete("/eclipse", -1);
	}
	@Test
	public void setData() throws KeeperException, InterruptedException{
		zkClient.setData("/app1", "imissyou".getBytes(), -1);
		byte[] data = zkClient.getData("/app1", false, null);
		System.out.println(new String(data));
	}
}
